package com.tuling.JUC;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 实现消息队列
 */
public class ProducerConsumer {
    ReentrantLock reentrantLock = new ReentrantLock();
    Condition condition = reentrantLock.newCondition();

    Object[] queue;
    private int size, count, takeStr, putStr;

    public void put(Object obj) {
        reentrantLock.lock();
        //判断是不是已将满了
        try {
            if (queue.length == size) {
                condition.await();
            }
            queue[count++] = obj;
            count++;
            putStr++;
            condition.signal();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            reentrantLock.unlock();
        }

    }

    public Object take() {
        reentrantLock.lock();
        Object obj = null;
        try {
            if (queue.length == 0) {
                condition.await();
            }
            obj = queue[takeStr];
            takeStr++;
            count--;
            condition.signal();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }finally {
            reentrantLock.unlock();
        }
       return obj;
    }

    public static void main(String[] args) {

    }
}
